import React, { useState, useEffect } from 'react';
import {
  Typography, Input, Select, Button, Divider, Row, Col, message,
  Card, Avatar, Statistic, Space, Tag, Tabs, Empty, Spin
} from 'antd';
import {
  SearchOutlined, DatabaseOutlined, FileOutlined, DownloadOutlined,
  EyeOutlined, TrophyOutlined, RocketOutlined, CloudUploadOutlined,
  CalendarOutlined, AppstoreOutlined, UnorderedListOutlined,
  ExclamationCircleOutlined, DeleteOutlined, HeartOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import TorrentList from '../components/TorrentList/TorrentList';
import { torrents, users } from '../services';
import { checkLocalStorageData, runFullDiagnosis } from '../utils/debugHelper';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const Resources = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [torrentsList, setTorrentsList] = useState([]);
  const [allTorrents, setAllTorrents] = useState([]); // 存储所有原始种子数据
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('categories');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedPromotion, setSelectedPromotion] = useState(''); // 新增：促销筛选
  const [messageApi, contextHolder] = message.useMessage();
  const [dataSource, setDataSource] = useState('OSS后端'); // 跟踪数据来源
  const [showLocalStorageInfo, setShowLocalStorageInfo] = useState(false); // 显示localStorage信息

  // 前端写死的8个资源分区
  const categoriesList = [
    {
      name: '电影',
      icon: 'film',
      description: '电影资源，包括各种类型的电影作品',
      color: '#1890ff'
    },
    {
      name: '电视剧',
      icon: 'tv',
      description: '电视剧集，包括国内外热门剧集',
      color: '#52c41a'
    },
    {
      name: '纪录片',
      icon: 'camera',
      description: '纪录片资源，探索真实世界',
      color: '#faad14'
    },
    {
      name: '动漫',
      icon: 'star',
      description: '动画片和漫画相关资源',
      color: '#eb2f96'
    },
    {
      name: '音乐',
      icon: 'sound',
      description: '音乐专辑、单曲等音频资源',
      color: '#722ed1'
    },
    {
      name: '图书',
      icon: 'book',
      description: '电子书籍、文档等阅读资源',
      color: '#13c2c2'
    },
    {
      name: '软件',
      icon: 'laptop',
      description: '各类软件工具和应用程序',
      color: '#fa541c'
    },
    {
      name: '游戏',
      icon: 'gamepad',
      description: '游戏资源，包括各平台游戏',
      color: '#2f54eb'
    }
  ];

  const iconMapping = {
    'film': FileOutlined,
    'tv': DatabaseOutlined,
    'camera': EyeOutlined,
    'star': TrophyOutlined,
    'sound': RocketOutlined,
    'book': FileOutlined,
    'laptop': CloudUploadOutlined,
    'gamepad': TrophyOutlined
  };

  useEffect(() => {
    // 启动时检查localStorage数据
    const localCheck = checkLocalStorageData();
    if (localCheck.exists && localCheck.count > 0) {
      console.log('⚠️ 检测到localStorage中有模拟数据，可能影响真实数据显示');
    }

    // 处理URL参数中的分类筛选
    const urlParams = new URLSearchParams(location.search);
    const categoryParam = urlParams.get('category');

    if (categoryParam) {
      console.log('🔗 从URL参数中获取分类:', categoryParam);
      setSelectedCategory(categoryParam);
      setActiveTab('list'); // 切换到列表视图
      messageApi.info(`正在筛选 "${categoryParam}" 分类的资源`);
    }

    // 只需要加载种子数据，分类已写死
    fetchTorrents();
  }, [location.search]);

  // 计算每个分类的统计信息
  const getCategoryStats = (categoryName) => {
    const categoryTorrents = allTorrents.filter(torrent =>
      torrent.classification === categoryName
    );

    // 计算总大小（以字节为单位）
    const totalBytes = categoryTorrents.reduce((sum, t) => sum + (t.sizeInBytes || 0), 0);

    // 计算促销种子数量
    const promotionTorrents = categoryTorrents.filter(t => t.promotion && t.promotion !== 'none');
    const doubleUploadTorrents = categoryTorrents.filter(t => t.promotion === 'double_upload');
    const freeDownloadTorrents = categoryTorrents.filter(t => t.promotion === 'free_download');

    const stats = {
      count: categoryTorrents.length,
      totalDownloads: categoryTorrents.reduce((sum, t) => sum + (t.downloads || t.download || 0), 0),
      totalSeeders: categoryTorrents.reduce((sum, t) => sum + (t.seeders || t.seeder || 0), 0),
      totalLikes: categoryTorrents.reduce((sum, t) => sum + (t.likes || t.upvote || 0), 0),
      totalSize: totalBytes, // 字节为单位，后续用formatSize函数格式化
      promotionCount: promotionTorrents.length,
      doubleUploadCount: doubleUploadTorrents.length,
      freeDownloadCount: freeDownloadTorrents.length
    };



    return stats;
  };

  const fetchTorrents = async () => {
    try {
      setLoading(true);
      console.log('📥 开始获取OSS种子数据...');

      // 优先使用OSS接口获取所有真实种子数据
      const response = await torrents.getAllUploadedTorrents();

      console.log('📊 OSS API响应:', response);

      if (response.success) {
        const rawTorrents = response.data.torrents || [];
        console.log('🔍 原始种子数据:', rawTorrents);

        // 检查是否为回退数据
        if (response.data.isLocalFallback) {
          console.warn('⚠️  当前使用的是本地存储回退数据');
          setDataSource('本地缓存');
          setShowLocalStorageInfo(true);
          messageApi.warning('网络连接失败，显示本地缓存数据');
        } else if (response.data.apiError) {
          console.warn('⚠️  API错误，显示空结果');
          setDataSource('API错误');
          messageApi.error('后端API错误，显示空结果');
        } else {
          console.log('✅ 使用真实OSS数据');
          setDataSource('OSS后端');
          setShowLocalStorageInfo(false);
        }

        // 适配数据格式
        const adaptedTorrents = adaptTorrentData(rawTorrents);
        console.log('🎯 适配后的种子数据:', adaptedTorrents);

        // 保存所有原始数据
        setAllTorrents(adaptedTorrents);

        // 根据当前筛选条件显示数据
        applyFilters(adaptedTorrents);

        const currentDataSource = response.data.source || 'Unknown';
        messageApi.success(`成功加载 ${response.data.total || 0} 个种子 (来源: ${currentDataSource})`);
      } else {
        messageApi.error('加载种子失败');
      }
    } catch (error) {
      console.error('❌ 加载种子失败:', error);
      messageApi.error('加载种子失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 前端实现筛选逻辑
  const applyFilters = (torrents = allTorrents) => {
    let filteredTorrents = [...torrents];

    // 按分类筛选
    if (selectedCategory) {
      filteredTorrents = filteredTorrents.filter(torrent =>
        torrent.classification === selectedCategory
      );
    }

    // 按促销类型筛选
    if (selectedPromotion) {
      filteredTorrents = filteredTorrents.filter(torrent =>
        torrent.promotion === selectedPromotion
      );
    }

    // 按搜索关键词筛选
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filteredTorrents = filteredTorrents.filter(torrent =>
        torrent.title?.toLowerCase().includes(keyword) ||
        torrent.name?.toLowerCase().includes(keyword) ||
        torrent.description?.toLowerCase().includes(keyword) ||
        torrent.comment?.toLowerCase().includes(keyword) ||
        torrent.uploader?.toLowerCase().includes(keyword)
      );
    }

    setTorrentsList(filteredTorrents);
    console.log(`🔍 筛选结果: ${filteredTorrents.length}/${torrents.length} 个种子`);
  };

  // 清除localStorage模拟数据
  const clearLocalStorageData = () => {
    try {
      localStorage.removeItem('starrypt_torrents');
      messageApi.success('已清除本地模拟数据');
      console.log('🗑️ 已清除localStorage中的种子数据');

      // 重新加载数据
      fetchTorrents();
    } catch (error) {
      console.error('清除本地数据失败:', error);
      messageApi.error('清除本地数据失败');
    }
  };

  // 强制使用OSS数据（无论网络状况）
  const forceUseOssData = async () => {
    try {
      setLoading(true);
      console.log('🚀 强制获取OSS数据...');

      // 清除localStorage种子数据，强制不回退
      localStorage.removeItem('starrypt_torrents');

      const response = await torrents.getAllUploadedTorrents();

      if (response.success && !response.data.isLocalFallback) {
        const adaptedTorrents = adaptTorrentData(response.data.torrents || []);
        setAllTorrents(adaptedTorrents);
        applyFilters(adaptedTorrents);
        setDataSource('OSS后端');
        setShowLocalStorageInfo(false);
        messageApi.success(`强制加载OSS数据成功: ${response.data.total || 0} 个种子`);
      } else {
        messageApi.error('无法获取OSS数据，可能是网络或服务器问题');
      }
    } catch (error) {
      console.error('强制获取OSS数据失败:', error);
      messageApi.error('强制获取OSS数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 前端搜索实现
  const handleSearch = (value) => {
    setSearchKeyword(value);
    setActiveTab('list'); // 搜索后切换到列表视图
    applyFilters(); // 使用统一的筛选函数

    if (value) {
      messageApi.success(`搜索 "${value}"`);
    }
  };

  // 分类筛选实现（调用后端API）
  const handleCategoryChange = async (value) => {
    setSelectedCategory(value);
    setActiveTab('list'); // 筛选后切换到列表视图

    if (value) {
      // 调用后端分类筛选API
      try {
        setLoading(true);
        console.log(`🔍 正在筛选分类: ${value}`);

        const response = await users.getTorrentsByClassification(value);

        if (response.success) {
          // 使用后端返回的分类种子数据，确保是数组格式
          const torrents = response.data.torrents || [];
          setTorrentsList(torrents);
          messageApi.success(`筛选 "${value}" 分类，找到 ${response.data.total || torrents.length} 个种子`);
          console.log(`✅ 后端分类筛选成功: ${response.data.total || torrents.length} 个种子`);
        } else {
          // 后端API失败，回退到前端筛选
          console.warn('后端分类筛选失败，回退到前端筛选:', response.message);
          applyFilters(); // 使用前端筛选作为回退
          messageApi.warning(`后端筛选失败，使用前端筛选: ${response.message}`);
        }
      } catch (error) {
        console.error('分类筛选API调用失败:', error);
        // 发生错误时也回退到前端筛选，确保torrentsList不会是undefined
        if (Array.isArray(allTorrents)) {
          applyFilters();
        } else {
          setTorrentsList([]); // 安全回退到空数组
        }
        messageApi.error(`分类筛选失败，使用前端筛选: ${error.message}`);
      } finally {
        setLoading(false);
      }
    } else {
      // 显示所有分类（重新加载所有数据），确保是数组格式
      setTorrentsList(Array.isArray(allTorrents) ? allTorrents : []);
      messageApi.success('显示所有分类');
    }
  };

  const handleCategoryClick = async (category) => {
    await handleCategoryChange(category.name);
  };

  // 促销筛选处理函数
  const handlePromotionChange = (value) => {
    setSelectedPromotion(value);
    setActiveTab('list'); // 筛选后切换到列表视图
    applyFilters(); // 重新应用筛选

    if (value) {
      const promotionNames = {
        'double_upload': '双倍上传量',
        'free_download': '下载免费',
        'none': '无促销'
      };
      messageApi.success(`筛选 "${promotionNames[value] || value}" 促销种子`);
    } else {
      messageApi.success('显示所有促销类型');
    }
  };

  const formatSize = (sizeInBytes) => {
    // 将字节转换为人类可读的大小格式
    const bytes = Number(sizeInBytes);
    if (!bytes || isNaN(bytes) || bytes <= 0) return '0 B';

    // 转换单位：字节 -> KB -> MB -> GB -> TB
    if (bytes >= 1024 * 1024 * 1024 * 1024) {
      return `${(bytes / (1024 * 1024 * 1024 * 1024)).toFixed(1)} TB`;
    } else if (bytes >= 1024 * 1024 * 1024) {
      return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
    } else if (bytes >= 1024 * 1024) {
      return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
    } else if (bytes >= 1024) {
      return `${(bytes / 1024).toFixed(1)} KB`;
    } else {
      return `${bytes} B`;
    }
  };

  // 格式化时间显示
  const formatTime = (timeString) => {
    if (!timeString) return '未知时间';

    try {
      const date = new Date(timeString);

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '时间格式错误';
      }

      const now = new Date();
      const diffMs = now.getTime() - date.getTime();
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      const diffMinutes = Math.floor(diffMs / (1000 * 60));

      // 相对时间显示（24小时内）
      if (diffMinutes < 60) {
        return diffMinutes <= 0 ? '刚刚' : `${diffMinutes}分钟前`;
      } else if (diffHours < 24) {
        return `${diffHours}小时前`;
      } else if (diffDays < 7) {
        return `${diffDays}天前`;
      } else if (diffDays < 30) {
        const weeks = Math.floor(diffDays / 7);
        return `${weeks}周前`;
      } else if (diffDays < 365) {
        const months = Math.floor(diffDays / 30);
        return `${months}个月前`;
      } else {
        const years = Math.floor(diffDays / 365);
        return `${years}年前`;
      }
    } catch (error) {
      console.warn('时间格式化失败:', timeString, error);
      return '时间解析失败';
    }
  };

  // 格式化完整日期时间（用于详情显示）
  const formatFullDateTime = (timeString) => {
    if (!timeString) return '未知时间';

    try {
      const date = new Date(timeString);

      if (isNaN(date.getTime())) {
        return '时间格式错误';
      }

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    } catch (error) {
      console.warn('完整时间格式化失败:', timeString, error);
      return '时间解析失败';
    }
  };

  // 适配OSS接口数据格式为前端期望格式
  const adaptTorrentData = (ossData) => {
    if (!Array.isArray(ossData)) return [];

    console.log('🔄 开始适配OSS数据:', ossData.length, '个种子');

    return ossData.map((torrent, index) => {
      // 处理促销类型：后端category字段表示促销类型，null表示无促销
      let promotion = 'none';
      if (torrent.category && torrent.category !== null) {
        promotion = torrent.category; // 直接使用后端返回的促销类型
      }

      const adapted = {
        ...torrent,
        // 将后端字段映射为前端期望字段
        title: torrent.name || torrent.title || '未命名种子',
        category: torrent.classification || '未分类', // classification是种子分类，用于显示
        classification: torrent.classification || '未分类', // 保留原始classification字段用于筛选
        uploadDate: torrent.fileTimestamps || torrent.uploadDate,
        uploader: torrent.uploader || '匿名用户',
        seeders: torrent.seeder || 0,
        leechers: 0, // OSS数据中没有leechers字段
        downloads: torrent.download || 0,
        likes: torrent.upvote || 0,
        views: torrent.watchs || 0, // 新增：浏览量字段
        size: torrent.size ? formatSize(torrent.size) : '未知大小',
        sizeInBytes: torrent.size || 0, // 保留原始字节数用于排序等功能
        description: torrent.comment || '暂无描述',
        // 注意：实际API返回的是 presource 和 tresource (小写)
        coverImage: torrent.presource || torrent.pResource || 'https://via.placeholder.com/300x450',
        torrentUrl: torrent.tresource || torrent.tResource || null,
        hash: torrent.hash || null,
        tags: [], // OSS数据中没有tags字段
        files: [], // OSS数据中没有files字段
        comments: [], // OSS数据中没有comments字段

        // 促销信息：使用后端真实的category字段
        promotion: promotion,

        // 格式化时间显示
        formattedUploadDate: formatTime(torrent.fileTimestamps || torrent.uploadDate),
        fullUploadDateTime: formatFullDateTime(torrent.fileTimestamps || torrent.uploadDate),

        // 保留原始时间戳用于排序等功能
        rawUploadDate: torrent.fileTimestamps || torrent.uploadDate
      };

      console.log('✅ 适配种子:', torrent.name, '→', adapted.title, '分类:', adapted.category, '促销:', adapted.promotion);
      return adapted;
    });
  };

  const renderCategoriesView = () => (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 300px)', padding: '24px 0' }}>
      <div style={{ textAlign: 'center', marginBottom: 32 }}>
        <Title level={2} style={{ marginBottom: 8 }}>
          <AppstoreOutlined /> 资源分区
        </Title>
        <Text type="secondary" style={{ fontSize: '16px' }}>
          按分类浏览不同类型的资源内容
        </Text>
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: '50px 0' }}>
          <Spin size="large" tip="加载分区信息..." />
        </div>
      ) : (
        <Row gutter={[24, 24]}>
          {categoriesList.map((category) => {
            const IconComponent = iconMapping[category.icon] || FileOutlined;
            const stats = getCategoryStats(category.name);

            return (
              <Col xs={24} sm={12} md={8} lg={6} key={category.name}>
                <Card
                  hoverable
                  style={{
                    height: '100%',
                    cursor: 'pointer',
                    transition: 'all 0.3s ease',
                    borderRadius: '12px',
                    overflow: 'hidden'
                  }}
                  onClick={() => handleCategoryClick(category)}
                  cover={
                    <div style={{
                      background: `linear-gradient(135deg, ${category.color}20, ${category.color}40)`,
                      padding: '32px',
                      textAlign: 'center'
                    }}>
                      <Avatar
                        size={80}
                        style={{
                          backgroundColor: category.color,
                          marginBottom: 16
                        }}
                        icon={<IconComponent style={{ fontSize: '36px' }} />}
                      />
                      <Title level={3} style={{ margin: 0, color: category.color }}>
                        {category.name}
                      </Title>
                    </div>
                  }
                  bodyStyle={{ padding: '20px' }}
                >
                  <div style={{ marginBottom: 16 }}>
                    <Text type="secondary" style={{ fontSize: '14px' }}>
                      {category.description}
                    </Text>
                  </div>

                  <Row gutter={[8, 8]} style={{ marginBottom: 16 }}>
                    <Col span={12}>
                      <Statistic
                        title="资源数量"
                        value={stats.count}
                        prefix={<FileOutlined />}
                        valueStyle={{ fontSize: '18px', color: category.color }}
                      />
                    </Col>
                    <Col span={12}>
                      <Statistic
                        title="总下载"
                        value={stats.totalDownloads}
                        prefix={<DownloadOutlined />}
                        valueStyle={{ fontSize: '18px', color: '#52c41a' }}
                      />
                    </Col>
                  </Row>

                  <Row gutter={[8, 8]} style={{ marginBottom: 16 }}>
                    <Col span={12}>
                      <Statistic
                        title="做种数"
                        value={stats.totalSeeders}
                        prefix={<EyeOutlined />}
                        valueStyle={{ fontSize: '18px', color: '#1890ff' }}
                      />
                    </Col>
                    <Col span={12}>
                      <Statistic
                        title="点赞数"
                        value={stats.totalLikes}
                        prefix={<HeartOutlined />}
                        valueStyle={{ fontSize: '18px', color: '#eb2f96' }}
                      />
                    </Col>
                  </Row>

                  {/* 促销信息显示 */}
                  {stats.promotionCount > 0 && (
                    <div style={{ marginBottom: 12 }}>
                      <Space size="small" wrap>
                        <Text type="secondary" style={{ fontSize: '12px' }}>
                          🎯 促销活动:
                        </Text>
                        {stats.doubleUploadCount > 0 && (
                          <Tag color="green" size="small" style={{ fontSize: '10px' }}>
                            ⬆️ {stats.doubleUploadCount}个双倍
                          </Tag>
                        )}
                        {stats.freeDownloadCount > 0 && (
                          <Tag color="orange" size="small" style={{ fontSize: '10px' }}>
                            🆓 {stats.freeDownloadCount}个免费
                          </Tag>
                        )}
                      </Space>
                    </div>
                  )}

                  <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    borderTop: '1px solid #f0f0f0',
                    paddingTop: '12px'
                  }}>
                    <Space>
                      <CalendarOutlined style={{ color: '#999' }} />
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        促销资源: {stats.promotionCount || 0}
                      </Text>
                    </Space>

                    <Tag color={category.color} style={{ margin: 0 }}>
                      {formatSize(stats.totalSize)}
                    </Tag>
                  </div>
                </Card>
              </Col>
            );
          })}
        </Row>
      )}
    </div>
  );

  const renderListView = () => (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Search
              placeholder="搜索种子名称、描述或标签"
              allowClear
              enterButton={<Button type="primary" icon={<SearchOutlined />}>搜索</Button>}
              size="large"
              onSearch={handleSearch}
            />
          </Col>
          <Col span={6}>
            <Select
              style={{ width: '100%' }}
              placeholder="选择分类 (后端API筛选)"
              value={selectedCategory || undefined}
              onChange={handleCategoryChange}
              size="large"
              allowClear
              loading={loading && selectedCategory}
            >
              <Option value="">所有分类</Option>
              <Option value="电影">🎬 电影</Option>
              <Option value="电视剧">📺 电视剧</Option>
              <Option value="纪录片">📹 纪录片</Option>
              <Option value="动漫">🎨 动漫</Option>
              <Option value="音乐">🎵 音乐</Option>
              <Option value="图书">📚 图书</Option>
              <Option value="软件">💻 软件</Option>
              <Option value="游戏">🎮 游戏</Option>
              <Option value="其他">📂 其他</Option>
            </Select>
          </Col>
          <Col span={6}>
            <Select
              style={{ width: '100%' }}
              placeholder="促销筛选"
              value={selectedPromotion || undefined}
              onChange={handlePromotionChange}
              size="large"
              allowClear
            >
              <Option value="">所有促销</Option>
              <Option value="none">无促销</Option>
              <Option value="double_upload">
                <span>
                  <span style={{ marginRight: 8 }}>⬆️</span>
                  双倍上传量
                </span>
              </Option>
              <Option value="free_download">
                <span>
                  <span style={{ marginRight: 8 }}>🆓</span>
                  下载免费
                </span>
              </Option>
            </Select>
          </Col>
        </Row>
      </div>

      {searchKeyword && (
        <div style={{ marginBottom: 16 }}>
          <Tag
            color="green"
            closable
            onClose={() => {
              setSearchKeyword('');
              handleSearch('');
            }}
            style={{ fontSize: '14px', padding: '4px 12px' }}
          >
            搜索: {searchKeyword}
          </Tag>
        </div>
      )}

      {(selectedCategory || selectedPromotion) && (
        <div style={{ marginBottom: 16 }}>
          <Space wrap>
            {selectedCategory && (
              <Tag
                color="blue"
                closable
                onClose={async () => {
                  setSelectedCategory('');
                  await handleCategoryChange(''); // 使用后端API处理清除分类
                }}
                style={{ fontSize: '14px', padding: '4px 12px' }}
              >
                分类: {selectedCategory}
                <Text type="secondary" style={{ fontSize: '10px', marginLeft: 4 }}>
                  (后端API)
                </Text>
              </Tag>
            )}
            {selectedPromotion && (
              <Tag
                color={
                  selectedPromotion === 'double_upload' ? 'green' :
                    selectedPromotion === 'free_download' ? 'orange' :
                      selectedPromotion === 'none' ? 'default' : 'purple'
                }
                closable
                onClose={() => {
                  setSelectedPromotion('');
                  applyFilters();
                }}
                style={{ fontSize: '14px', padding: '4px 12px' }}
              >
                促销: {
                  selectedPromotion === 'double_upload' ? '⬆️ 双倍上传量' :
                    selectedPromotion === 'free_download' ? '🆓 下载免费' :
                      selectedPromotion === 'none' ? '无促销' :
                        selectedPromotion
                }
              </Tag>
            )}
          </Space>
        </div>
      )}

      <Divider orientation="left">
        种子列表 {selectedCategory && `(${selectedCategory})`}
        <Text type="secondary" style={{ fontSize: '14px', marginLeft: 8 }}>
          共 {torrentsList.length} 个资源
        </Text>
      </Divider>

      {torrentsList.length === 0 && !loading ? (
        <Empty
          description="暂无种子数据"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          style={{ padding: '50px 0' }}
        >
          <Button type="primary" onClick={fetchTorrents} icon={<DatabaseOutlined />}>
            重新加载
          </Button>
        </Empty>
      ) : (
        <TorrentList torrents={torrentsList} loading={loading} />
      )}
    </div>
  );

  return (
    <div>
      {contextHolder}



      <div style={{ marginBottom: 24 }}>
        <Title level={2} style={{ marginBottom: 8 }}>
          <DatabaseOutlined /> 资源中心
        </Title>
        <Text type="secondary" style={{ fontSize: '16px' }}>
          发现和管理所有类型的资源内容
        </Text>
      </div>

      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        size="large"
        style={{ marginBottom: 24 }}
      >
        <TabPane
          tab={
            <span>
              <AppstoreOutlined />
              分区浏览
            </span>
          }
          key="categories"
        >
          {renderCategoriesView()}
        </TabPane>
        <TabPane
          tab={
            <span>
              <UnorderedListOutlined />
              列表浏览
            </span>
          }
          key="list"
        >
          {renderListView()}
        </TabPane>
      </Tabs>
    </div>
  );
};

export default Resources; 